<template>
  <view class="container" :style="containerStyle">
    <!-- 单头像显示 -->
    <image v-if="avatars.length === 1" class="avatar" :style="singleAvatarStyle" :src="getAvatarUrl(avatars[0])"
      mode="aspectFill"></image>

    <!-- 多头像组显示 -->
    <template v-else>
      <image v-for="(item, index) in displayAvatars" :key="index" class="avatar-group" :class="index > 0 ? 'boder' : ''"
        :style="getAvatarStyle(index)" :src="getAvatarUrl(item)" mode="aspectFill"></image>
      <!-- 显示剩余数量 -->
      <view v-if="showExtra" class="avatar-extra" :style="extraStyle">
        +{{ extraCount }}
      </view>
    </template>
  </view>
</template>

<script setup>
import { computed } from 'vue';

const props = defineProps({
  avatars: {
    type: Array,
    default: () => []
  },
  // 图片尺寸（单位rpx）
  size: {
    type: String,
    default: 64
  },
  // 对象键名
  keyName: {
    type: String,
    default: ''
  },
  // 头像间距（单位rpx）
  gap: {
    type: Number,
    default: -18
  },
  showExtra: {
    type: Boolean,
    default: false
  }
});

// 计算显示的头像
const displayAvatars = computed(() => props.avatars.slice(0, 3));
// 计算额外数量
const extraCount = computed(() => props.avatars.length - 3);
// 是否显示额外数量
// const showExtra = computed(() => props.avatars.length > 3);

// 容器样式
let num = Number(displayAvatars.value.length > 1 ? displayAvatars.value.length - 1 : 0)

// 图片为 三张时 间隙应该减去 2*props.gap
let size = Number(props.size) + Math.abs(num * Number(props.gap))

// 父盒子的宽高计算
const containerStyle = computed(() => ({
  width: `${Number(size) + 12}rpx`,
  height: `${Number(props.size) + 12}rpx`,
}));
// 单个头像样式
const singleAvatarStyle = computed(() => ({
  width: `${props.size}rpx`,
  height: `${props.size}rpx`
}));

// 获取头像URL
const getAvatarUrl = (item) => {
  return props.keyName ? item[props.keyName] : item;
};
// 头像组样式
const getAvatarStyle = (index) => {
  return {
    width: `${props.size}rpx`,
    height: `${props.size}rpx`,
    left: !index ? `${index * Math.abs(props.gap)}rpx` : `${index * Math.abs((props.gap - 3))}rpx`,
    zIndex: index + 1
  };
};

// 额外数量样式
const extraStyle = computed(() => ({
  width: `${props.size}rpx`,
  height: `${props.size}rpx`,
  left: `${(props.avatars.length - 1) * Math.abs(props.gap)}rpx`,
  fontSize: `${props.size * 0.3}rpx`,
  lineHeight: `${props.size}rpx`
}));
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  display: flex;
  align-items: center;

  .boder {
    border: 6rpx solid rgba(255, 255, 255, 0.7, );
  }

  .avatar,
  .avatar-group {
    position: absolute;
    border-radius: 50%;
    // border: 2rpx solid #fff;
    // box-sizing: border-box;
    z-index: 1;
    border-radius: 50%;
    flex-shrink: 0;
    // box-shadow: 0 10px 20px rgba(0,0,0,0.2);
  }

  .avatar-extra {
    position: absolute;
    border-radius: 50%;
    background-color: #c0c4cc;
    color: white;
    text-align: center;
    border: 2rpx solid #fff;
  }
}
</style>
